/*
 *  Copyright (c) 2021@boostmerlin<https://github.com/boostmerlin/summer-boot>
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in all
 *  copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 */

package io.summer.gadget.channel.core.autoconfig;

import io.summer.basis.excepts.AppException;
import io.summer.gadget.channel.SummerChannel;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

/**
 * 为每一个
 *
 * @author Moonlight
 */
@Slf4j
public class ChannelProxy implements InvocationHandler {
  private final Class<?> channelClientType;
  private final SummerChannel summerChannel;
  private final Map<Method, ListenerMethod> methodCache;

  public ChannelProxy(Class<?> channelClientType, SummerChannel summerChannel) {
    this.channelClientType = channelClientType;
    methodCache = new ConcurrentHashMap<>();
    this.summerChannel = summerChannel;
  }

  @SuppressWarnings("unchecked")
  public <T> T newInstance() {
    return (T) Proxy.newProxyInstance(channelClientType.getClassLoader(),
      new Class[]{channelClientType}, this);
  }

  private ListenerMethod cachedMapperMethod(Method method) {
    ListenerMethod listenerMethod = methodCache.get(method);
    if (listenerMethod == null) {
      listenerMethod = new ListenerMethod(channelClientType, method, summerChannel);
      methodCache.put(method, listenerMethod);
    }
    return listenerMethod;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (Object.class.equals(method.getDeclaringClass())) {
      try {
        return method.invoke(this, args);
      } catch (Throwable t) {
        throw new AppException(t);
      }
    }
    if (args.length != 1) {
      throw new AppException("Topic method args should be 1.");
    }

    final ListenerMethod listenerMethod = cachedMapperMethod(method);
    return listenerMethod.apply(args[0]);
  }

  /**
   * @author Moonlight
   */
  public static class ListenerMethod implements Function<Object, Object> {
    private final SummerChannel summerChannel;
    private final String topic;
    private final Type returnType;

    public ListenerMethod(Class<?> listenerInterface, Method method, SummerChannel channel) {
      summerChannel = channel;
      returnType = method.getGenericReturnType();
      topic = ChannelTopicNameHelper.getTopic(method, listenerInterface);
    }

    @Override
    public Object apply(Object o) {
      return summerChannel.publish(topic, returnType, o);
    }
  }
}
